<template>
  <div class="largeScreen fcbc">
    <div class="flex-1 h1 leftBox fcbc fv">
      <div class="cur w1" @click="gotoback">
        <el-image style="height: 50px" :src="require(`@/assets/images/windPower/detailBack.png`)" fit="fill"></el-image>
      </div>
      <div class="maxTitle pl10 pt20 pb20 w1">{{ this.fengji }}</div>
      <div class="cwhite  w1 flex-1 fcbc fv">
        <div class="titleBg flc w1">设备信息</div>
        <div class="itemBox fcbc fw flex-1" style="width: 100%;">
          <div class="flc w1 borBottom" v-for="(model, idx) in modelList" :key="idx">
            <div class="nameBox f12">{{ model.name }}：</div>
            <div class="f12">{{ model.value }}</div>
          </div>
        </div>
      </div>
      <div class="cwhite w1 mt20 flex-1 fcbc fv">
          <div class="titleBg flc w1">环境监测</div>
          <div class="itemBox fcbc fw f14 p20 flex-1">
            <div class="flc w1 mb10" v-for="(temp, idx) in temperatureData" :key="idx">
              <div style="width: 70px; min-width: 70px">{{ temperatureLabels[idx] }}</div>
              <div class="flex-1 ml10 mr10">
                <el-progress :stroke-width="10" :percentage="temp" :show-text="false" define-back-color="#FCCF5B33"
                  :stroke-linecap="'square'" :color="getTextColor(idx)"></el-progress>
              </div>
              <div>{{ temp }}{{ getUnit(idx) }}</div>
            </div>
          </div>
        </div>

    </div>
    <div class="flex-2 h1 flb contentBox">
      <div class="cwhite w1 ml20 mr10">
        <div class="titleBg flc">统计参数</div>
        <div class="itemBox fcbc f14 p20" style="align-items: stretch !important">
          <div class="flex-2 flc fw">
            <div class="flex2 mb10">
              <div class="mr10">
                <div class="pl10 f12">年发电量</div>
                <div class="flc tjcsBg">
                  <!-- <div class="f10">{{ tjcs.nfdl }}</div> -->

                  <count-to v-if="showConcentTop6" class="f10" :start-val="0" :end-val="Number(tjcs.nfdl)" :duration="3000"
                    :autoplay="true"></count-to>
                  <div class="f10">万kwh</div>
                </div>
              </div>
            </div>
            <div class="flex2 mb10" style="display: none;">
              <div class="mr10">
                <div class="pl10 f12">负荷率</div>
                <div class="flc tjcsBg">
                  <!-- <div class="f10">{{ tjcs.fhl }}</div> -->

                  <count-to v-if="showConcentTop7" class="f10" :start-val="0" :end-val="Number(tjcs.fhl)" :duration="3000"
                    :autoplay="true"></count-to>
                  <div class="f10">万kwh</div>
                </div>
              </div>
            </div>
            <div class="flex2 mb10">
              <div class="mr10">
                <div class="pl10 f12">月发电量</div>
                <div class="flc tjcsBg">
                  <!-- <div class="f10">{{ tjcs.yfdl }}</div> -->

                  <count-to v-if="showConcentTop8" class="f10" :start-val="0" :end-val="Number(tjcs.yfdl)" :duration="3000"
                    :autoplay="true"></count-to>
                  <div class="f10">万kwh</div>
                </div>
              </div>
            </div>
            <div class="flex2 mb10">
              <div class="mr10">
                <div class="pl10 f12">平均风速</div>
                <div class="flc tjcsBg">
                  <!-- <div class="f10">{{ tjcs.pjfs }}</div> -->

                  <count-to v-if="showConcentTop9" class="f10" :start-val="0" :end-val="Number(tjcs.pjfs)" :duration="3000"
                    :autoplay="true"></count-to>
                  <div class="f10">m/s</div>
                </div>
              </div>
            </div>
            <div class="flex2 mb10">
              <div class="mr10">
                <div class="pl10 f12">日发电量</div>
                <div class="flc tjcsBg">
                  <!-- <div class="f10">{{ tjcs.rfdl }}</div> -->

                  <count-to v-if="showConcentTop10" class="f10" :start-val="0" :end-val="Number(tjcs.rfdl)" :duration="3000"
                    :autoplay="true"></count-to>
                  <div class="f10">万kwh</div>
                </div>
              </div>
            </div>
            <div class="flex2 mb10">
              <div class="mr10">
                <div class="pl10 f12">最大风速</div>
                <div class="flc tjcsBg">
                  <!-- <div class="f10">{{ tjcs.zdfs }}</div> -->

                  <count-to v-if="showConcentTop11" class="f10" :start-val="0" :end-val="Number(tjcs.zdfs)" :duration="3000"
                    :autoplay="true"></count-to>
                  <div class="f10">m/s</div>
                </div>
              </div>
            </div>
            <div class="flex2">
              <div class="mr10">
                <div class="pl10 f12">实时功率</div>
                <div class="flc tjcsBg">
                  <!-- <div class="f10">{{ tjcs.zgl }}</div> -->

                  <count-to v-if="showConcentTop12" class="f10" :start-val="0" :end-val="Number(tjcs.zgl)" :duration="3000"
                    :autoplay="true"></count-to>
                  <div class="f10">万kw</div>
                </div>
              </div>
            </div>
          </div>
          <div class="flex-3">
            <lineChartJd :fsData="fsData" :glData="glData" :fsglDataX="fsglDataX"></lineChartJd>
          </div>
        </div>
      </div>
    </div>
    <div class="flex-1 h1 rightBox fcbc fv">
      <div class="frc timeBox w1">
        <div class="flc">
          <div class="flc cblue">
            <div class="cblue">{{ currentDate }}</div>
          </div>
          <div class="cwhite ml20">{{ currentTime }}</div>
        </div>
      </div>
      <div class="flex-1 fcbc fv"><div class="cwhite w1" style="min-height: 245px;">
        <div class="titleBg flc">运行数据</div>
        <div class="itemBox fcbc fw f14 p10" style="align-items: baseline;">
          <div class="flc flex2 mb10" v-for="(item, idx) in yunxingList" :key="idx">
            <div class="itemTitle f10">{{ item.name }}</div>
            <!-- <div class="numBox cgreen f10">{{ item.num }}</div> -->

            <count-to v-if="showConcentTop5" class="numBox cgreen f10" :start-val="0" :end-val="item.num"
              :duration="3000" :autoplay="true"></count-to>
            <div class="f10">{{ item.unit }}</div>
          </div>
        </div>
      </div>
      <div class="cwhite mt20 fcbc fv flex-1 w1">
        <div class="titleBg flc w1">运行监测</div>
        <div class="itemBox p10 mt10 flex-1 w1 fcbc fv">
          <div class="tabsBox flc w1">
            <div class="tabsItem flex-1 mr10 fcc cur f12" :class="tabsIdx == 2 ? 'tabsSel' : ''" @click="tabsSelFun(1)">
              实时信息</div>
            <div class="tabsItem flex-1 fcc cur f12" :class="tabsIdx == 1 ? 'tabsSel' : ''" @click="tabsSelFun(2)">故障信息
            </div>
          </div>
          <div class="flex-1 w1 scroll-list-container" v-show="table1" @mouseenter="stopScroll"
            @mouseleave="startScroll">
            <el-table :data="visibleData" style="width: 100%;height: 100%;" :show-header="false"
              class="mt10 f12 h1 yxjc scroll-table" stripe :row-class-name="tableRowClassName">
              <el-table-column prop="content" label="名字"></el-table-column>
              <el-table-column prop="time" label="日期" width="100"></el-table-column>
            </el-table>
          </div>
          <div class="flex-1 w1 scroll-list-container" v-show="table2" @mouseenter="stopScroll"
            @mouseleave="startScroll1">
            <el-table :data="visibleData1" style="width: 100%;height: 100%;" :show-header="false"
              class="mt10 f12 h1 yxjc scroll-table" stripe :row-class-name="tableRowClassName">
              <el-table-column prop="content" label="名字"></el-table-column>
              <el-table-column prop="time" label="日期" width="100"></el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      </div>
    </div>
  </div>
</template>

<script>
import lineChartJd from "./chart/lineChartJd.vue";
import CountTo from 'vue-count-to';
import { getYxsj, getTjcs, getYxjc, getGlFs, getHjjc, getSbxx } from "@/api/dp/fengJiDetail"
export default {
  name: "fengJiDetail",
  components: { lineChartJd, CountTo },
  data() {
    return {
      showConcentTop5: true,
      showConcentTop6: true,
      showConcentTop7: true,
      showConcentTop8: true,
      showConcentTop9: true,
      showConcentTop10: true,
      showConcentTop11: true,
      showConcentTop12: true,
      windFarm: {},
      // 统计参数折线风速
      fsData: [],
      // 统计参数折线功率
      glData: [],
      fsglDataX: [],
      currentDate: "",
      currentTime: "",
      // 环境监测
      temperatureData: [70, 30, 90], // 接口返回的温度数据
      temperatureLabels: ["环境温度", "机舱温度", "齿轮箱温度"], // 对应的标签
      // 设备信息
      modelList: [],
      //风机参数
      fengji: {},
      // 统计参数
      tjcs: {
        nfdl: 0,
        fhl: 0,
        yfdl: 0,
        pjfs: 0,
        rfdl: 0,
        zdfs: 0,
        zgl: 0,
      },
      yunxingList: [
        {
          name: "实时功率",
          num: 0,
          unit: "kw",
        },
        {
          name: "风机转速",
          num: 0,
          unit: "转/分钟",
        },
        {
          name: "风机电流",
          num: 0,
          unit: "A",
        },
        {
          name: "风机电压",
          num: 0,
          unit: "V",
        },
        {
          name: "风机能耗",
          num: 0,
          unit: "kwh",
        },
        {
          name: "当日发电量",
          num: 0,
          unit: "kwh",
        },
        {
          name: "累计发电量",
          num: 0,
          unit: "kwh",
        },
        {
          name: "节约标煤",
          num: 0,
          unit: "t",
        },
        {
          name: "减排二氧化碳",
          num: 0,
          unit: "m³",
        },
      ],
      selectTab: "实时信息",
      tableData: [],
      visibleData: [],
      visibleData1: [],
      visibleCount: 10,
      currentIndex: 0,
      scrollInterval: null,
      table1: true,
      table2: false,
      tabsIdx: 1,
    };
  },
  methods: {
    // 下面接口都需要穿上个页面点进来的id,由于地图页面找的前端没开发完这里先用死的
    // 运行数据
    yxsj() {
      // console.log(this.windFarm)
      // console.log(this.windFarm.windTurbineId)
      // var id =  this.fengji.id;
      getYxsj(this.windFarm.windTurbineId).then(response => {

        this.yunxingList = response
      })
    },
    // 运行监测
    yxjc() {
      this.visibleData = []
      this.visibleData1 = []
      // var id =  this.fengji.id;
      getYxjc(this.windFarm.windTurbineId, "1").then(response => {
        this.tableData = response
        // 初始化显示前10条数据
        this.visibleData = this.tableData.slice(0, this.visibleCount);
        this.visibleData1 = this.tableData.slice(0, this.visibleCount);
      })

      // 开始滚动
      this.startScroll();
    },
    // 统计参数
    tjcsA() {
      // var id =  this.fengji.id;
      getTjcs(this.windFarm.windTurbineId).then(response => {
        this.tjcs = response
      })
    },
    // 环境监测
    hjjc() {
      // var id =  this.fengji.id;
      getHjjc(this.windFarm.windTurbineId).then(response => {
        this.temperatureLabels = response.name
        this.temperatureData = response.value
      })
    },
    // 统计参数折线图
    glfs() {
      // var id =  this.fengji.id;
      getGlFs(this.windFarm.windTurbineId).then(response => {
        this.fsData = response.fs;
        this.glData = response.gl;
        this.fsglDataX = response.fsglDataX;
      })
    },
    // 设备信息
    sbxx() {
      // var id =  this.fengji.id;
      getSbxx(this.windFarm.windTurbineId).then(response => {
        this.modelList = response
      })
    },
    // 年月日时分秒
    updateDateTime() {
      const now = new Date();

      // 格式化日期（YYYY-MM-DD 星期X）
      const weekdays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const weekday = weekdays[now.getDay()];
      this.currentDate = `${year}-${month}-${day} ${weekday}`;

      // 格式化时间（HH:MM:SS）
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");
      this.currentTime = `${hours}:${minutes}:${seconds}`;
    },
    // 环境监测相关
    getUnit(idx) {
      if (idx <= 2) return "℃";
      if (idx === 3) return "m/s";
      return "KPa";
    },
    getTextColor(idx) {
      if (idx <= 2) return "#FCCF5B";
      if (idx === 3) return "#10D865";
      return "#0AA7FF";
    },
    tableRowClassName({ row, rowIndex }) {
      return row.type === "2" ? 'error-row' : '';
    },
    gotoback() {
      this.$router.go(-1);
    },
    startScroll() {
      if (this.tabsIdx === 1 && !this.hasErrorRows()) {
        this.stopScroll(); // Clear any existing interval
        this.scrollInterval = setInterval(() => {
          this.scrollUp();
        }, 2000);
      }
    },
    startScroll1() {
      this.stopScroll(); // Clear any existing interval
      this.scrollInterval = setInterval(() => {
        this.scrollUp1();
      }, 2000);
    },

    stopScroll() {
      if (this.scrollInterval) {
        clearInterval(this.scrollInterval);
        this.scrollInterval = null;
      }
    },

    hasErrorRows() {
      // Check if any visible row has type=2
      return this.visibleData.some(row => row.type === "2");
    },
    tabsSelFun(i) {
      this.visibleData = [];
      this.visibleData1 = [];
      this.tableData = [];
      this.tabsIdx = i;
      this.currentIndex = 0; // Reset scroll position
      if (i == 1) {
        this.table1 = true
        this.table2 = false
        this.stopScroll(); // Stop any existing scroll

        getYxjc(this.$route.query.windTurbineId, i).then(response => {
          this.tableData = response;
          this.visibleData = this.tableData.slice(0, this.visibleCount);
          this.visibleData1 = this.tableData.slice(0, this.visibleCount);

          // Auto-adjust container height
          this.$nextTick(() => {
            this.adjustContainerHeight();

            // Start scrolling only if it's real-time info and no errors
            if (i === 1 && !this.hasErrorRows()) {
              this.startScroll();
            }
          });
        });
      } else {
        this.table2 = true
        this.table1 = false
        this.startScroll1();

        getYxjc(this.$route.query.windTurbineId, i).then(response => {
          this.tableData = response;
          this.visibleData = this.tableData.slice(0, this.visibleCount);
          this.visibleData1 = this.tableData.slice(0, this.visibleCount);

          // Auto-adjust container height
          this.$nextTick(() => {
            this.adjustContainerHeight();

            this.startScroll1();
          });
        });
      }

    },

    adjustContainerHeight() {
      const container = document.querySelector('.scroll-list-container');
      if (container) {
        const rowHeight = 40; // Approximate row height
        const maxHeight = rowHeight * this.visibleCount;
        const contentHeight = rowHeight * this.visibleData.length;
        container.style.height = `${Math.min(maxHeight, contentHeight)}px`;
      }
    },

    scrollUp1() {
      if (this.tableData.length <= this.visibleCount) return;

      this.currentIndex++;

      // If reached bottom, go back to top
      if (this.currentIndex > this.tableData.length - this.visibleCount) {
        this.currentIndex = 0;
      }

      // Add animation
      this.addAnimation();

      // Update data after animation
      setTimeout(() => {
        this.visibleData1 = this.tableData.slice(
          this.currentIndex,
          this.currentIndex + this.visibleCount
        );
      }, 300);
    },
    scrollUp() {

      // Don't scroll if there are error rows
      if (this.hasErrorRows()) {
        this.stopScroll();
        return;
      }

      if (this.tableData.length <= this.visibleCount) return;

      this.currentIndex++;

      // If reached bottom, go back to top
      if (this.currentIndex > this.tableData.length - this.visibleCount) {
        this.currentIndex = 0;
      }

      // Add animation
      this.addAnimation();

      // Update data after animation
      setTimeout(() => {
        this.visibleData = this.tableData.slice(
          this.currentIndex,
          this.currentIndex + this.visibleCount
        );
      }, 300);
    },

    addAnimation() {
      const tableBody = document.querySelector('.scroll-table .el-table__body-wrapper');
      if (tableBody) {
        tableBody.style.transition = 'transform 0.3s ease-out';
        tableBody.style.transform = 'translateY(-30px)';

        setTimeout(() => {
          tableBody.style.transition = 'none';
          tableBody.style.transform = 'translateY(0)';
        }, 300);
      }
    },

    // 定时器15分钟加载一次
    // 增强版数据刷新方法
    async refreshData() {
      try {
        await Promise.all([
          // 初始化加载
          this.yxsj(),
          this.yxjc(),
          this.hjjc(),
          this.sbxx(),
          this.tjcsA(),
          this.glfs(),
          this.showConcentTop5 = false,
          this.showConcentTop6 = false,
          this.showConcentTop7 = false,
          this.showConcentTop8 = false,
          this.showConcentTop9 = false,
          this.showConcentTop10 = false,
          this.showConcentTop11 = false,
          this.showConcentTop12 = false,
          this.$nextTick(() => {
            this.showConcentTop5 = true,
              this.showConcentTop6 = true,
              this.showConcentTop7 = true,
              this.showConcentTop8 = true,
              this.showConcentTop9 = true,
              this.showConcentTop10 = true,
              this.showConcentTop11 = true,
              this.showConcentTop12 = true
          })
        ]);
        console.log('数据刷新成功', new Date().toLocaleString());
      } catch (error) {
        console.error('数据刷新失败:', error);
      }
    },

    // 初始化定时器
    initRefreshTimer() {
      // 先清除旧定时器
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval);
      }
      // 设置定时器 (1分钟)
      this.refreshInterval = setInterval(() => {
        this.refreshData();
      }, 60000);
    }
  },
  watch: {
    // Watch for changes in visibleData to check for error rows
    visibleData: {
      handler(newVal) {
        if (this.hasErrorRows()) {
          this.stopScroll();
        }
      },
      deep: true
    }
  },

  mounted() {
    // 初始化定时刷新
    this.initRefreshTimer();

    this.$nextTick(() => {
      this.adjustContainerHeight();
    });
    let windTurbineId = this.$route.query.windTurbineId;
    let windTurbinename = this.$route.query.windTurbinename;
    this.windFarm = {
      windTurbineId: windTurbineId,
      windTurbinename: windTurbinename
    }

    this.fengji = windTurbinename;
    // 初始化加载
    this.yxsj()
    this.yxjc()
    this.hjjc()
    this.sbxx()
    this.tjcsA()
    this.glfs()
    // 初始更新
    this.updateDateTime();

    // 每秒更新一次
    this.timer = setInterval(this.updateDateTime, 1000);
  },
  beforeDestroy() {
    // 清除定时器，防止内存泄漏
    clearInterval(this.timer);
    // 清除定时器
    this.stopScroll();
  },
};
</script>

<style scoped lang="scss">
.scroll-list-container {
  overflow: hidden;
  position: relative;
  transition: height 0.3s ease;
}

::v-deep .el-table .error-row {
  color: #ff5c5c !important;
}

::v-deep .el-table .error-row td {
  background-color: rgba(255, 92, 92, 0.1) !important;
}

.scroll-table {
  height: 100%;
}

/* 隐藏原生滚动条 */
.scroll-table .el-table__body-wrapper {
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.scroll-table .el-table__body-wrapper::-webkit-scrollbar {
  display: none;
}

/* 表格行样式 */
.scroll-table .el-table__row {
  transition: all 0.3s ease;
  height: 40px;
  line-height: 40px;
}

/* 表格单元格样式 */
.scroll-table .el-table__cell {
  padding: 0 10px;
}






.largeScreen {
  width: 100%;
  height: 100%;
  background: url("~@/assets/images/windPower/detail-fenj-bg.png") #000f21;
  background-size: 100% 100%;
  position: relative;
  padding: 15px;
}

::v-deep .el-table .warning-row {
  color: #ffd15c !important;
}

::v-deep .el-table .success-row {
  color: #ffd15c !important;
}

.cwhite {
  color: #ffffff;
}

.cblue {
  color: #45a2ff;
}

.cgray {
  color: #999999;
}

.cgreen {
  color: #36f5f7;
}

.maxTitle {
  font-size: 30px;
  color: #ffffff;
  font-weight: bold;
}

.titleBg {
  background-image: url("~@/assets/images/icon/detail-fenj-title.png");
  background-size: 100% 100%;
  height: 30px;
  padding-left: 25px;
  position: relative;
  overflow: hidden;

  // 光影流动效果
  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg,
        rgba(255, 255, 255, 0),
        rgba(82, 181, 230, 0.7),
        rgba(255, 255, 255, 0));
    transform: skewX(-25deg);
    animation: lightFlow 4s ease-in-out infinite;
    z-index: 1;
  }

  // 文字增强效果
  >* {
    position: relative;
    z-index: 2;
    text-shadow: 0 0 8px rgba(0, 170, 255, 0.7);
    transition: all 0.3s ease;
  }

  &:hover>* {
    text-shadow: 0 0 12px rgba(0, 170, 255, 1);
  }
}

@keyframes lightFlow {
  0% {
    left: -100%;
    opacity: 0.5;
  }

  70% {
    opacity: 1;
  }

  100% {
    left: 100%;
    opacity: 0;
  }
}

.flex2 {
  flex: 0 0 50%;
}

.timeBox {
  height: 125px;
}

.itemBox {
  min-height: 215px;
  background: linear-gradient(#071b431a, #0d2e59cc);

  .itemTitle {
    width: 60px;
  }

  .numBox {
    background-color: #06244880;
    border-top: 1px solid #1b7ef2;
    border-bottom: 1px solid #1b7ef2;
    padding: 8px 0;
    margin: 0 5px;
    width: 40px;
    text-align: center;
  }
}

.tabsItem {
  border: 1px solid #0aa7ff;
  background: linear-gradient(to bottom, #1b7df200, #1b7df299);
  padding: 8px 0;
}

.tabsSel {
  background: #1b7df21a;
}

.tjcsBg {
  background-image: url("~@/assets/images/icon/tjcsBg.png");
  background-size: 100% 100%;
  padding: 5px;
  margin-top: 5px;
}

.flex2 {
  flex: 0 0 50%;
}

.nameBox {
  width: 80px;
}

.borBottom {
  border-bottom: 1px solid #1c7ef333;
  padding: 0 10px;
  height: calc(100% / 10);
}

.leftBox {
  width: 500px;
}

.rightBox {
  width: 500px;
}

.contentBox {
  width: calc(100% - 1000px);
}

// 表格
::v-deep .el-table__body-wrapper {
  font-size: 12px !important;
}

::v-deep .el-table__body-wrapper table {
  display: block !important;
  overflow: auto;
}

::v-deep .el-table__body-wrapper tbody {
  height: 100% !important;
}

// 表格
::v-deep .yxjc .el-table__row {
  width: 100%;
  // display: flex;
  // justify-content: space-between;
}

::v-deep .yxjc .el-table__cell {
  width: 50%;
  text-align: center;
}

::v-deep .el-table,
.el-table__expanded-cell {
  background-color: transparent !important;
}

::v-deep .el-table::before {
  height: 0px;
}

::v-deep .el-table th {
  background-color: #153864cc !important;
  border-bottom: none !important;
  color: #36f5f7;
}

::v-deep .el-table tr {
  background-color: transparent !important;
  color: #ffffff;
  height: 35.8px;
}

::v-deep .el-table td {
  padding: 5px 0 !important;
}

::v-deep .el-table--enable-row-transition .el-table__body td,
::v-deep .el-table .cell {
  background-color: transparent !important;
  border: none !important;
  padding: 0 !important;
  line-height: normal;
}

/* 覆盖element-ui的圆角样式 */
.el-progress-bar__outer {
  border-radius: 0 !important;
}

.el-progress-bar__inner {
  border-radius: 0 !important;
}
</style>
